package burubaka.controller.mnt;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import net.arnx.jsonic.JSON;

import org.apache.commons.lang3.StringUtils;
import org.slim3.controller.Navigation;

import burubaka.common.controller.Controller;
import burubaka.model.RaceCardHorse;
import burubaka.model.RaceInfo;
import burubaka.service.RaceCardHorseService;
import burubaka.service.RaceInfoService;

/**
 * @author tk
 * 
 */
public class RaceCardController extends Controller {

	private static final Logger log = Logger.getLogger(RaceCardController.class.getName());

	private RaceInfoService raceInfoService = new RaceInfoService();
	private RaceCardHorseService raceCardHorseService = new RaceCardHorseService();

	/**
	 * 検索
	 * 
	 * @return Navigation
	 * @throws Exception
	 */
	public Navigation search() throws Exception {

		Map<String, Object> resMap = new HashMap<String, Object>();
		RaceInfo raceInfo = null;
		List<RaceCardHorse> list = null;
		String proc = (String) reqMap.get("proc");
		String raceKey = (String) reqMap.get("raceURL");
		if (StringUtils.isEmpty(raceKey)) {
			raceKey = (String) reqMap.get("raceKey");
		}
		if (proc != null && proc.equals("mod")) {
			raceInfo = raceInfoService.getRaceInfoByRaceDate(raceKey);
			list = raceCardHorseService.getRaceCardHorseList(raceInfo);
		} else {
			String text = raceInfoService.getURLNomiText(raceKey);
			raceInfo = raceInfoService.getRaceInfo(text, raceKey);
			String rcText = RaceCardHorseService.getURLText(raceInfo);
			list = raceCardHorseService.getRaceCardHorseList(raceInfo, rcText);
		}
		resMap.put("raceInfo", raceInfo);
		resMap.put("rcHorseL", list);

		String jsonText = JSON.encode(resMap, true);

		log.info(jsonText);

		response.setContentType("application/json; charset=UTF-8");
		response.getWriter().write(jsonText);
		response.getWriter().flush();

		return null;
	}

	/**
	 * 登録
	 * 
	 * @return Navigation
	 * @throws Exception
	 */
	public Navigation regist() throws Exception {
		RaceInfo raceInfo = raceInfoService.regist(reqMap, 1);
		raceCardHorseService.regist(reqMap, raceInfo);

		return null;
	}

}
